package com.qixiaobao.common.core.domain.entity;

import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import org.apache.pdfbox.util.Matrix;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 获取pdf每页每行的坐标位置
 * @Author yangxm
 */
public class PositionPDFTextStripper extends PDFTextStripper {

    private String pageNum;
    //页面，每行的第一个Y坐标集合
    private Map<Integer, List<PdfCoordinate>> firstLineInfos = new HashMap<>();
    private Map<Integer, List<PdfCoordinate>> lastLineInfos = new HashMap<>();

    private Boolean startOfLine = true;

    public PositionPDFTextStripper() throws IOException {
        super();
    }

    @Override
    public void processTextPosition(TextPosition text) {
        super.processTextPosition(text);

        PDColor strokingColor = getGraphicsState().getStrokingColor();
        PDColor nonStrokingColor = getGraphicsState().getNonStrokingColor();
        RenderingMode renderingMode = getGraphicsState().getTextState().getRenderingMode();
    }

    @Override
    public void startPage(PDPage page) throws IOException {
        super.startPage(page);
        startOfLine = true;
    }

    @Override
    public void endPage(PDPage page) throws IOException {
        super.endPage(page);
    }

    @Override
    public void writeLineSeparator() throws IOException {
        super.writeLineSeparator();
        startOfLine = true;
    }

    @Override
    public void writeString(String text, List<TextPosition> textPositions) throws IOException {
        if (startOfLine) {
            TextPosition firstProsition = textPositions.get(0);
            Matrix textMatrix = firstProsition.getTextMatrix();

            int currentPageNo = this.getCurrentPageNo();

            if(firstLineInfos.containsKey(currentPageNo)) {
                PdfCoordinate coordinate = new PdfCoordinate();
                coordinate.setY(textMatrix.getTranslateY());
                coordinate.setX(textMatrix.getTranslateX());
                firstLineInfos.get(currentPageNo).add(coordinate);
            }else {
                List<PdfCoordinate> info = new ArrayList<>();
                firstLineInfos.put(currentPageNo, info);
            }
            startOfLine = false;
        }
        super.writeString(text, textPositions);
    }

    public Map<Integer, List<PdfCoordinate>> getFirstLineInfos() { return firstLineInfos; }

    public Map<Integer, List<PdfCoordinate>> getLastLineInfos() { return lastLineInfos; }
}
